var isEdit;
var lastRowID;

$(function() {
	var parent = getIframeSize();
	scwidth =  parent.width-1;
	scheight = parent.height-74;
	
	init();
	
	gsjqgird();
	
});

function init(){
	isEdit = false;
	lastRowID = "";
}

function gsjqgird(){
	var dateSearchOptions = {
			sopt:['eq','ne','lt','le','gt','ge']
		}
	//带有初始化日期的
	var dateSearchOptions1 = {
				sopt:['eq','ne','lt','le','gt','ge'],
				dataInit:function(jElem) { 
					jElem.datepicker({
						beforeShow:function(i,e){e.dpDiv.css('z-index',105); }
					});
				} 
	}
	
	var fn_editSubmit=function(response,postdata){ 
		var json=response.responseText; 
		alert(json);//显示返回值 
	} 
	
	var editOptions={ 
		top: 50, left: "100", width: 800  
		,closeOnEscape: true, afterSubmit: fn_editSubmit 
	} 
	
	
	
	$("#gstable").jqGrid({        	    	
    	url: "goods.do?type=show",
    	mtype: 'POST',	   
    	datatype: "json",	//更改使用json数据   
    	width: scwidth,
    	height: scheight,    	
    	colNames: ['商品ID','商品名称','商品编号','详细描述','是否有效','商品类别','商品品牌','是否上架','商品单价','到货时间','条码','显示顺序','图片'],
    	colModel: [
    		{name:'GOODS_ID',index:'GOODS_ID',align:'center',hidden:true,search:false},    		
    		{name:'GOODS_NAME',index:'GOODS_NAME',align:'center',editable:true,searchoptions:dateSearchOptions},
    		{name:'GOODS_SN',index:'GOODS_SN',align:'left',editable:true,searchoptions:dateSearchOptions},
    		{name:'GOODS_COMMENT',index:'GOODS_COMMENT',align:'left',editable:true,searchoptions:dateSearchOptions},
    		{name:'GOODS_ACTIVE',index:'GOODS_ACTIVE',align:'center',editable:true,searchoptions:dateSearchOptions},
    		{name:'GOODS_TYPE',index:'GOODS_TYPE',align:'center',editable:true,searchoptions:dateSearchOptions},
    		{name:'GOODS_BRAND',index:'GOODS_BRAND',align:'center',editable:true,searchoptions:dateSearchOptions},
    		{name:'GOODS_SHELVE',index:'GOODS_SHELVE',align:'center',editable:true,searchoptions:dateSearchOptions},
    		{name:'GOODS_PRICE',index:'GOODS_PRICE',align:'center',editable:true,searchoptions:dateSearchOptions},
    		{name:'GOODS_ARRIVE_DATE',index:'GOODS_ARRIVE_DATE',align:'center',editable:true,searchoptions:dateSearchOptions1,editoptions:{dataInit:function(jElem) {$( jElem).datepicker({
						beforeShow:function(i,e){e.dpDiv.css('z-index',999); }
					}); }}},
    		{name:'GOODS_BAR_CODE',index:'GOODS_BAR_CODE',align:'center',editable:true,searchoptions:dateSearchOptions},
    		{name:'GOODS_ORDER',index:'GOODS_ORDER',align:'center',editable:true,searchoptions:dateSearchOptions},
    		{name:'GOODS_IMAGE',index:'GOODS_IMAGE',align:'center',editable:true,searchoptions:dateSearchOptions}		
    	],
    	pager: 'gspager',		//分页工具栏
    	sortname: 'GOODS_ID',	//排序
    	loadonce:false,			//每次都从服务器加载数据
    	rownumbers: true,    	//序列
    	gridview: true,			//提高加载速度
    	sortorder: "asc",    	
    	imgpath: 'images', 		//图片存放路径  
    	rowNum: 25,				//每页显示记录数
    	viewrecords: true,     	//是否显示行数
    	jsonReader:{  
            repeatitems : false, 	//指明每行的数据是可以重复的，如果设为false，则会从返回的数据中按名字来搜索元素，这个名字就是colModel中的名字
            id : "0"
        },         
    	rowList:[25,50,100],		//可调整每页显示的记录数
    	multiselect: true, 			//是否支持多选  
    	editurl:"goods.do?type=add",
    	caption: "商品列表",
    	onSelectRow:function(id){
    		if(!isEdit){
    			return false;
    		}
    		//如果勾选复选框，则不编辑
    		if(event.srcElement && event.srcElement.nodeName ==="INPUT" &&  event.srcElement.type ==="checkbox" && event.srcElement.className.indexOf("cbox") >=0)
	   		{
	   			
	   			saveUnfinishTable();
	   			return false;
	   		}else{
	   			if(id && id!==lastRowID){
	   				if(lastRowID) {						
						$('#gstable').saveRow(lastRowID,null,"clientArray",null);	
					}
					$('#gstable').editRow(id,true,onEdit(id),null,"clientArray",null);
					
	   			}else if(id && id == lastRowID){
	   				$('#gstable').editRow(id,true,onEdit(id),null,"clientArray",null);
	   			}
	   			
	   			function onEdit(rowid){
					$.each($("#gstable select.editable option"),function(i,n){
						if(!$(n).attr("title"))
						{
							if($(n).text()){$(n).attr("title",$(n).text());}
						}
					});
											
				}
	   			
	   			lastRowID = id;
	   			
	   			$("tbody tr", $("#gstable")).removeClass("ui-state-highlight");
				$("[id^=jqg_]",$("#gstable")).attr("checked",false);
				$("#cb_jqg",$("#gstable").parent().parent()).attr("checked",false);
				$("#gstable").setGridParam("selarrrow",[]);
	   		}
	   		return false;
	   	},
	    loadComplete: function() { 	  	 
	    	$("#ui-datepicker-div").hide();
	    	
	    	if(!isEdit){
	    		$("#gs_save").readonly();
	    		$("#gs_delete").readonly();
	    		$("#add_gstable").readonly();
	    	}
	    } 
    }).navGrid('#gspager',{search:p_gs_search,refresh:p_gs_refresh,edit:false,add:p_gs_add,del:false,searchtext:"查找",refreshtext:"刷新",addtext:"添加"},editOptions,{},{},{},{multipleSearch:true});
    
     if(p_gs_delete){
    	 jQuery("#gstable").navButtonAdd("#gspager",{
    	 	id : "gs_delete",
			caption : "删除",
			title: '删除商品',
			buttonicon : 'ui-icon-trash',
			onClickButton: deletegoods,
			position : "first",
			cursor : 'pointer'
		});
    }
    
    if(p_gs_save){
    	 jQuery("#gstable").navButtonAdd("#gspager",{
    	 	id : "gs_save",
			caption : "保存",
			title: '保存商品',
			buttonicon : 'ui-icon-disk',
			onClickButton: savegoods,
			position : "first",
			cursor : 'pointer'
		});
    }
    
   
    
    /*if(p_gs_add){
    	 jQuery("#gstable").navButtonAdd("#gspager",{
    	 	id : "gs_add",
			caption : "增加",
			title: '增加商品',
			buttonicon : 'ui-icon-plus',
			onClickButton: addgoods,
			position : "first",
			cursor : 'pointer'
		});
    }*/
    
    if(p_gs_update){
    	 jQuery("#gstable").navButtonAdd("#gspager",{
    	 	id : "gs_update",
			caption : "编辑",
			title: '编辑商品',
			buttonicon : 'ui-icon-pencil',
			onClickButton: updategoods,
			position : "first",
			cursor : 'pointer'
		});
    }
    
}

//添加商品
function addgoods(){
	
}

//删除商品
function deletegoods(){
	var selectedRowID = $("#gstable").getGridParam("selarrrow");
	if(selectedRowID.length > 0){		
		if(window.confirm("确认删除?")){
			var postData = {rowID:selectedRowID};
				$.ajax({
					type: 'POST',
					url:  "goods.do?type=deleteGoods",
					dataType: "json",
					data: postData,
					success: function(data){
						var result = data;
						alert(result.msg);
						$("#gstable").setGridParam({url: "goods.do?type=show"}).trigger("reloadGrid");
			    	},
			    	error: function(data){
		           		alert('删除失败！');
		        	}
				});
		}
	}else{
		alert("请选择要删除的行");
		return false;
	}
}

//编辑商品
function updategoods(){
	if(!isEdit){
		isEdit = true;
		$("#gs_save").readonly(false);
		$("#gs_delete").readonly(false);
		$("#add_gstable").readonly(false);
	}else{
		isEdit = false;
		$("#gs_save").readonly();
		$("#gs_delete").readonly();
		$("#add_gstable").readonly();
		saveUnfinishTable();
	}
}

//保存商品
function savegoods(){
	saveUnfinishTable();
	var postData = {
		GOODS_ID:[],
		GOODS_NAME:[],
		GOODS_SN:[],
		GOODS_COMMENT:[],
		GOODS_ACTIVE:[],
		GOODS_TYPE:[],
		GOODS_BRAND:[],
		GOODS_SHELVE:[],
		GOODS_PRICE:[],
		GOODS_ARRIVE_DATE:[],
		GOODS_BAR_CODE:[],
		GOODS_ORDER:[],
		GOODS_IMAGE:[]
	}
	
	var ids = $("#gstable").getDataIDs();
	
	$.each(ids,function(i,n){	
		var rowData = $("#gstable").getRowData(n);
		postData.GOODS_ID[i] = rowData.GOODS_ID,
		postData.GOODS_NAME[i] = rowData.GOODS_NAME,
		postData.GOODS_SN[i] = rowData.GOODS_SN,
		postData.GOODS_COMMENT[i] = rowData.GOODS_COMMENT,
		postData.GOODS_ACTIVE[i] = rowData.GOODS_ACTIVE,
		postData.GOODS_TYPE[i] = rowData.GOODS_TYPE,
		postData.GOODS_BRAND[i] = rowData.GOODS_BRAND,
		postData.GOODS_SHELVE[i] = rowData.GOODS_SHELVE,
		postData.GOODS_PRICE[i] = rowData.GOODS_PRICE,
		postData.GOODS_ARRIVE_DATE[i] = rowData.GOODS_ARRIVE_DATE,
		postData.GOODS_BAR_CODE[i] = rowData.GOODS_BAR_CODE,
		postData.GOODS_ORDER[i] = rowData.GOODS_ORDER,
		postData.GOODS_IMAGE[i] = rowData.GOODS_IMAGE
	});
	
	$.ajax({
		type: 'POST',
		url:  "goods.do?type=saveGoods",
		dataType: "json",
		data: postData,
		success: function(data){
			var result = data;
			alert(result.msg);
			$("#gstable").setGridParam({url: "goods.do?type=show"}).trigger("reloadGrid");
    	},
    	error: function(data){
          		alert('保存失败！');
       	}
	});
}

//客户端保存
function saveUnfinishTable()
{
	var ids = $("#gstable").getDataIDs();
	$.each(ids,function(i,id){
		ind = $("#gstable").getInd(id,true);
		editable = $(ind).attr("editable");
		if(editable === "1")
		{
			$('#gstable').saveRow(id,null,"clientArray",null);
		}
	});
	
}

